package br.com.onlinebidding.mb;

import java.io.Serializable;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import br.com.onlinebidding.facade.EdictFacade;
import br.com.onlinebidding.facade.ProductFacade;
import br.com.onlinebidding.model.Edict;

@SessionScoped
@ManagedBean(name = "edictMB")
public class EdictMB extends AbstractMB implements Serializable {
	
	public static final String INJECTION_NAME = "#{edictMB}";
	private static final long serialVersionUID = 1L;

	private Edict edict;
	private List<Edict> edicts;
	private EdictFacade edictFacade;
	private ProductFacade productFacade = new ProductFacade();
	private int id;

	public EdictFacade getEdictTFacade() {
		if (this.edictFacade == null) {
			this.edictFacade = new EdictFacade();
		}

		return this.edictFacade;
	}

	public void insertEdict() {
		
		id = this.edict.getIdProduct().getId();
	
	  try {
			getEdictTFacade().insertEdict(this.edict);
			
			closeDialog();
			displayInfoMessageTo("Inserido Com Sucesso!");
			loadEdicts();
			resetEdict();
		} catch (Exception e) {
			keepDialogOpen();
			displayErrorMessageTo("Ops, erro ao inserir . Tente novamente mais tarde!");
			e.printStackTrace();
		}
	  
	  productFacade.updateInUse(id);
		
	}

	public void updateEdict() {
		
		id = this.edict.getIdProduct().getId();
		try {
			getEdictTFacade().updateEdict(this.edict);
			closeDialog();
			displayInfoMessageTo("Alterado Com Sucesso!");
			loadEdicts();
			resetEdict();
		} catch (Exception e) {
			keepDialogOpen();
			displayErrorMessageTo("Ops, erro ao alterar . Tente novamente mais tarde!");
			e.printStackTrace();
		}
		 productFacade.updateInUse(id);
	}

	public void deleteEdict() {
		try {
			getEdictTFacade().deleteEdict(this.edict);
			closeDialog();
			displayInfoMessageTo("Excluido Com Sucesso!");
			loadEdicts();
			resetEdict();
		} catch (Exception e) {
			keepDialogOpen();
			displayErrorMessageTo("Ops, erro ao excluir  . Tente novamente mais tarde!");
			e.printStackTrace();
		}
	}

	public List<Edict> getAllEdicts() {
		if (this.edicts == null) {
			loadEdicts();
		}

		return this.edicts;
	}
	
	public List<Edict> getAllEdictsAssets() {
		if (this.edicts == null) {
			loadEdictsAssets();
		}

		return this.edicts;
	}

	private void loadEdicts() {
		this.edicts = getEdictTFacade().listAll();
	}
	
	private void loadEdictsAssets() {
		this.edicts = getEdictTFacade().listAllAssets();
	}

	public void resetEdict() {
		this.edict = new Edict();
	}


	public Edict getEdict() {
		return this.edict;
	}

	public void setEdict(Edict edict) {
		this.edict = edict;
	}

}